package de.tuberlin.dima.dkey.server;

import java.io.File;
import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.Executors;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

public class Server {

	static Logger logger = Logger.getLogger(Server.class);

	
    public static void main(String[] args) throws Exception {
    	
		//Set up the logging
	    BasicConfigurator.configure();
	    
	    Logger.getRootLogger().setLevel(Level.INFO);
	    
        // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Configure the pipeline factory.
        bootstrap.setPipelineFactory(new ServerPipelineFactory());
        
        //Set up the DB
        TreeDB db = new TreeDB();
		
//        Scanner input=new Scanner(System.in); // Decl. & init. a Scanner.
//        System.out.println("A");
//        String nayme=input.next(); // Get what the user types.
//        System.out.println("B");
        
        
        
        long time = System.currentTimeMillis();
        
        
        //load in all the data
        String filename = "test.db";
        boolean exists = (new File(filename)).exists();
        if (exists) {
        	db.loadDB(filename);
        } else {
            db.setDbName(filename);
        }
		System.out.println("Loading trees took " + (System.currentTimeMillis() - time) + " milliseconds");

		//db.serialize();
		
        ServerHandler.setDB(db);
        
        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(8080));
        
        logger.info("Server up and running");
    }
}
